package com.xxgc.demo.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.xxgc.demo.controller.pojo.PictureRecyclingPOJO;
import com.xxgc.demo.controller.result.Result;
import com.xxgc.demo.utils.ImageCompressUtil;
import com.xxgc.demo.utils.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author: lxy
 * @Date :2023/10/7 - 10 - 07 - 19:46
 * 文件上传
 */
@Slf4j
@Tag(name = "文件上传中心")
@RestController
@RequestMapping("/file")
public class FilesController {

    //redis工具类
    @Autowired
    private RedisUtil redisUtil;

    @Parameters({
            @Parameter(name = "file",description = "图片",required = true),
            @Parameter(name = "model",description = "模块",required = true),
    })
    @Operation(summary = "图片上传",description = "图片上传")
    @PostMapping(value = "/uploadImg")
    public Result uploadImg(MultipartFile file,String model) throws IOException {
        //---------------文件类型校验-----------------------
        String type = file.getContentType();
        log.info("类型："+type);
        //是否以 image/ 开头
        if(!type.startsWith("image/")){
            return Result.error().msg("请上传图片格式的文件（jpg、jpeg、png、gif...）");
        }
        //----------------文件大小-------------------------
        long size = file.getSize();//当前大小
        long maxsize = 5 * 1024 * 1024;//5M
        if(size > maxsize){
            return Result.error().msg("上传图片不能大于2M");
        }

        //1、保存在本地  2、保存在OSS
        //保存地址
        String path = "C:\\uploadImg\\"+model+"\\";
        //获取文件名
        String fileName = file.getOriginalFilename();
        //修改文件名防止覆盖
        String simpleUUID = IdUtil.simpleUUID();
        //获取文件后缀
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        //加时间分割，方便滚动删除
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        path += time + "\\";
        //如果没有文件路径就创建文件路径
        File file2 = new File(path);
        if(!file2.exists()){
            file2.mkdirs();//创建文件夹
        }
        //压缩后的标清图片 地址
        String path_1 = path + simpleUUID + "_1" + fileSuffix;
        //缩略图地址
        String path_2 = path + simpleUUID + "_2" + fileSuffix;
        //地址
        path += simpleUUID + fileSuffix;


        File file1 = new File(path);

        //------------------   水印 hutool   -------------------
        //获取图片宽高
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        int width = bufferedImage.getWidth()/2-100-10;
        log.info("width:"+width);
        int height = bufferedImage.getHeight()/2-50-10;
        log.info("height:"+height);

        //保存到本地
        file.transferTo(file1);

        ImgUtil.pressImage(
                FileUtil.file(path),//原图
                FileUtil.file(path),//加水印之后的图
                ImgUtil.read(FileUtil.file(System.getProperty("user.dir")+
                        "\\src\\main\\resources\\image\\watermark\\watermark.png")), //水印图片
                width, //x坐标修正值。 默认在中间，偏移量相对于中间偏移
                height, //y坐标修正值。 默认在中间，偏移量相对于中间偏移
                1
        );


        //------------------   2-5M的 图片压缩 大于5M的图片提示不能超过2M ---------------
        long maxsize4 = 4 * 1024 * 1024;//4M
        long maxsize3 = 3 * 1024 * 1024;//3M
        long maxsize2 = 2 * 1024 * 1024;//2M

        //大于2M小于5M就进行压缩
        if(size >= maxsize4){ //大于4M
            ImageCompressUtil.imageCompress(path,path_1, (float) 0.3);
        }else if(size >= maxsize3){ //大于3M
            ImageCompressUtil.imageCompress(path,path_1, (float) 0.4);
        }else if(size >= maxsize2){ //大于2M
            ImageCompressUtil.imageCompress(path,path_1, (float) 0.5);
        }

        //-----------------------缩略图-------------------------
        //原图
        //_1压缩后的图
        //_2缩略图
        ImageCompressUtil.imageCompress(path,path_2, 200);

        //虚拟路径地址
        String virtualPath = "/images/"+model+ "/" + time + "/" + simpleUUID + fileSuffix;



        //----------------------垃圾回收信息------------------------
        PictureRecyclingPOJO recyclingPOJO = new PictureRecyclingPOJO(path, path_1, path_2, LocalDateTime.now());
        String key = "junk_images";
        //list的方式存储
        redisUtil.lSet(key,recyclingPOJO);
        String key1 = "recycling:image:"+simpleUUID;
        //60秒后删除
        redisUtil.set(key1,recyclingPOJO,60);


        //返回一个上传成功之后的地址
        return Result.ok().data(virtualPath).msg("图片上传成功");
    }



    /*@Operation(summary = "纯文件上传")
    @PostMapping(value = "/upload")
    public Result uploadFile(List<MultipartFile> fileList){
        return Result.ok("上传成功");
    }*/

}